﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyBlog.Common;
using MyBlog.Model;
using Webdiyer.WebControls.Mvc;

namespace MyBlog.Web.Controllers
{
    public class SystemController : BaseController
    {
        [TrackRequest]
        public ActionResult Message(int page = 1)
        {
            var mess = new MessageModel { IsSystem = true };
            var list = XiaoBoKe.MessageService.GetAll(mess, false).OrderByDescending(x => x.MsgTime).ToPagedList(page, 20);
            if (Request.IsAjaxRequest())
            {
                return PartialView("_SysMessageManager", list);
            }
            return View(list);
        }

        [HttpPost]
        [Authenticate(false)]
        public JsonResult DeleteMsg(int id)
        {
            //不能这样筛选，删不了
            var replyItems = XiaoBoKe.MsgReplyService.GetAll(new MsgReplyModel { MsgId = id }, false);
            if (replyItems.Count > 0)
            {
                DelRpMsg(replyItems);
            }
            XiaoBoKe.MessageService.Delete(id);
            return Json(new JsonData { State = AjaxState.Success });
        }

        void DelRpMsg(List<MsgReplyModel> items)
        {
            foreach (var item in items)
            {
                if (item.MsgReplyModels.Count > 0)
                {
                    DelRpMsg(item.MsgReplyModels);
                }
                if (XiaoBoKe.MsgReplyService.Get(item.ID) != null)
                {
                    XiaoBoKe.MsgReplyService.Delete(item.ID);
                }
            }
        }

        [HttpPost]
        [Authenticate(false)]
        public JsonResult DeleteRpMsg(int id)
        {
            XiaoBoKe.MsgReplyService.Delete(id);
            return Json(new JsonData { State = AjaxState.Success });
        }

        [HttpPost]
        public JsonResult SendMsg(MessageModel model)
        {
            //后台已关闭游客留言功能，并且没有用户登入
            if (!WebCache.AllowAnonymous && UserSession.LoginUserInfo == null)
            {
                return Json(new JsonData { State = AjaxState.Fail, Message = "抱歉，操作失败，管理员已在后台关闭了游客留言权限！" });
            }
            model.VisitorIP = UserSession.GetClientIP();
            model.MsgTime = DateTime.Now;
            XiaoBoKe.MessageService.Add(model);
            string uname = !string.IsNullOrWhiteSpace(model.VisitorName) ? "【游客】" + model.VisitorName : "【用户】" + WebCache.GetNickName(model.VisitUid);
            var notice = uname + "说：" + model.Content.StripHTML();
            EmailHelper.SendMail(WebCache.SystemMail, "小博客有新的留言", notice);
            if (UserSession.LoginUserInfo != null)
            {
                base.AddNotice(UserSession.AccountId, NoticeEnum.SendMsgToSys, null, model.Content);
            }
            return Json(new JsonData { State = AjaxState.Success });
        }

        [HttpPost]
        [Authenticate(false)]
        public JsonResult ReplyMsg(int mid, int? rid, string content)
        {
            var model = new MsgReplyModel { MsgId = mid, ParentID = (rid == 0 ? null : rid), Content = content, ReplyTime = DateTime.Now, ReplyUid = UserSession.LoginUserInfo.Account };
            XiaoBoKe.MsgReplyService.Add(model);
            try
            {
                var item = XiaoBoKe.MessageService.Get(mid);
                if (!item.AccountId.Same(UserSession.AccountId))
                {
                    string email = !string.IsNullOrWhiteSpace(item.VisitorEmail) ? item.VisitorEmail : (WebCache.GetAccount(item.VisitUid).Email);
                    var notice = (UserSession.LoginUserInfo.IsAdmin ? "【管理员】" : "【用户】") + WebCache.GetNickName(UserSession.AccountId) + "回复你说：" + content.StripHTML();
                    EmailHelper.SendMail(email, "小博客留言回复通知", notice);
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("发送留言回复通知出错：" + ex.Message);
            }
            return Json(new JsonData { State = AjaxState.Success });
        }

        [TrackRequest]
        public ActionResult BugList(int page = 1)
        {
            var total = XiaoBoKe.BugService.GetAll(false).Where(x => x.Parent == null).Count();
            ViewBag.total = total;
            return View();
        }

        [HttpPost]
        public JsonResult SendBug(int? pid, string bugDetail, string visitor, string uid, string visEmail, string bugType)
        {
            //后台已关闭游客留言功能，并且没有用户登入
            if (!WebCache.AllowAnonymous && UserSession.LoginUserInfo == null)
            {
                return Json(new JsonData { State = AjaxState.Fail, Message = "抱歉，操作失败，管理员已在后台关闭了游客留言权限！" });
            }
            var bug = new BugModel { ParentID = (pid == 0 ? null : pid), BugDetail = bugDetail, Visitor = visitor, VisitorEmail = visEmail, Uid = uid, BugType = bugType, SendTime = DateTime.Now };
            XiaoBoKe.BugService.Add(bug);
            string uname = !string.IsNullOrWhiteSpace(visitor) ? "【游客】" + visitor : "【用户】" + WebCache.GetNickName(uid);
            var notice = uname + "说：" + bugDetail.StripHTML();
            EmailHelper.SendMail(WebCache.SystemMail, "小博客有新的bug反馈", notice);
            if (UserSession.LoginUserInfo != null)
            {
                base.AddNotice(UserSession.AccountId, NoticeEnum.SendBugToSys, null, bugDetail);
            }
            return Json(new JsonData { Data = bug.ID, State = AjaxState.Success });
        }

        [Authenticate(false)]
        public JsonResult DelBug(int id)
        {
            var bugRpList = XiaoBoKe.BugService.GetAll(new BugModel { ParentID = id }, false);
            if (bugRpList.Count > 0)
            {
                DelRpBugs(bugRpList);
            }
            XiaoBoKe.BugService.Delete(id);
            return Json(new JsonData { State = AjaxState.Success });
        }

        public JsonResult DelRpBug(int id)
        {
            XiaoBoKe.BugService.Delete(id);
            return Json(new JsonData { State = AjaxState.Success });
        }

        void DelRpBugs(List<BugModel> items)
        {
            foreach (var item in items)
            {
                if (item.BugList.Count > 0)
                {
                    DelRpBugs(item.BugList);
                }
                if (XiaoBoKe.BugService.Get(item.ID) != null)
                {
                    XiaoBoKe.BugService.Delete(item.ID);
                }
            }
        }

        [Authenticate(false)]
        public JsonResult ReplyBug(int? pid, string content)
        {
            var bugrp = new BugModel { ParentID = (pid == 0 ? null : pid), BugDetail = content, SendTime = DateTime.Now, Uid = UserSession.LoginUserInfo.Account };
            XiaoBoKe.BugService.Add(bugrp);
            try
            {
                var item = XiaoBoKe.BugService.Get(pid);
                if (!item.Uid.Same(UserSession.AccountId))
                {
                    string email = !string.IsNullOrWhiteSpace(item.VisitorEmail) ? item.VisitorEmail : (WebCache.GetAccount(item.Uid).Email);
                    var notice = (UserSession.LoginUserInfo.IsAdmin ? "【管理员】" : "【用户】") + WebCache.GetNickName(UserSession.AccountId) + "回复你说：" + content.StripHTML();
                    EmailHelper.SendMail(email, "小博客Bug回复通知", notice);
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("发送Bug回复通知出错：" + ex.Message);
            }
            return Json(new JsonData { Data = bugrp.ID, State = AjaxState.Success });
        }

        public PartialViewResult _SysBugManager(int page = 1)
        {
            var buglist = XiaoBoKe.BugService.GetAll(false).Where(x => x.Parent == null).OrderByDescending(x => x.SendTime).ToPagedList(page, 10);
            return PartialView(buglist);
        }

        [Authenticate(false)]
        [HttpPost]
        public JsonResult AgreeMsg(int id)
        {
            var model = XiaoBoKe.MessageService.Get(id);
            if (string.IsNullOrWhiteSpace(model.AgreeUsers) || (!string.IsNullOrWhiteSpace(model.AgreeUsers) && !model.AgreeUsers.Contains(UserSession.AccountId)))
            {
                XiaoBoKe.MessageService.AddAgree(id, UserSession.AccountId);
                return Json(new JsonData { State = AjaxState.Success });
            }
            else
            {
                return Json(new JsonData { State = AjaxState.Fail, Message = "你已经点过赞啦！" });
            }
        }

        [Authenticate(false)]
        [HttpPost]
        public JsonResult AgreeMsgReply(int id)
        {
            var model = XiaoBoKe.MsgReplyService.Get(id);
            if (string.IsNullOrWhiteSpace(model.AgreeUsers) || (!string.IsNullOrWhiteSpace(model.AgreeUsers) && !model.AgreeUsers.Contains(UserSession.AccountId)))
            {
                XiaoBoKe.MsgReplyService.AddAgree(id, UserSession.AccountId);
                return Json(new JsonData { State = AjaxState.Success });
            }
            else
            {
                return Json(new JsonData { State = AjaxState.Fail, Message = "你已经点过赞啦！" });
            }
        }

        [Authenticate(false)]
        [HttpPost]
        public JsonResult AgreeBug(int id)
        {
            var model = XiaoBoKe.BugService.Get(id);
            if (string.IsNullOrWhiteSpace(model.AgreeUsers) || (!string.IsNullOrWhiteSpace(model.AgreeUsers) && !model.AgreeUsers.Contains(UserSession.AccountId)))
            {
                XiaoBoKe.BugService.AddAgree(id, UserSession.AccountId);
                return Json(new JsonData { State = AjaxState.Success });
            }
            else
            {
                return Json(new JsonData { State = AjaxState.Fail, Message = "你已经点过赞啦！" });
            }
        }

        public PartialViewResult _LoginTip()
        {
            return PartialView();
        }

        public ActionResult About()
        {
            var sys = XiaoBoKe.SysInfoService.Get(1);
            var md5 = UserSession.GetClientInfoMD5<SysInfoModel>("read1" + UserSession.AccountId);
            if (CookieHelper.GetCookie(md5) == null)
            {
                var cookie = new HttpCookie(md5, "read");
                cookie.Expires = DateTime.Now.AddHours(24 - DateTime.Now.Hour);
                CookieHelper.AddCookie(cookie);
                XiaoBoKe.SysInfoService.AddRead(1);
                sys.ReadCount++;
            }
            return View(sys);
        }

        [HttpPost]
        public JsonResult AgreeSys(int type)
        {
            var md5 = UserSession.GetClientInfoMD5<SysInfoModel>("agree" + type + UserSession.AccountId);
            if (CookieHelper.GetCookie(md5) == null)
            {
                var cookie = new HttpCookie(md5, "agree");
                cookie.Expires = DateTime.Now.AddHours(24 - DateTime.Now.Hour);
                CookieHelper.AddCookie(cookie);
                XiaoBoKe.SysInfoService.AddAgree(type);
                return Json(new JsonData { State = AjaxState.Success });
            }
            return Json(new JsonData { State = AjaxState.Fail, Message = "你今天已经点过赞了哦，明天可以再来点哒^_^" });
        }

        [TrackRequest]
        public ActionResult TimeAxis()
        {
            var sys = XiaoBoKe.SysInfoService.Get(2);
            var records = XiaoBoKe.SysHistoryService.GetAll();
            var md5 = UserSession.GetClientInfoMD5<SysInfoModel>("read2" + UserSession.AccountId);
            if (CookieHelper.GetCookie(md5) == null)
            {
                var cookie = new HttpCookie(md5, "read");
                cookie.Expires = DateTime.Now.AddHours(24 - DateTime.Now.Hour);
                CookieHelper.AddCookie(cookie);
                XiaoBoKe.SysInfoService.AddRead(2);
                sys.ReadCount++;
            }
            ViewBag.sys = sys;
            return View(records);
        }
    }
}
